package com.onion.utils.utils;

import com.alibaba.fastjson.JSON;

public class ByteUtils {

    /**
     * Object转为son字符串后，字节数组
     * @param data
     * @return
     */
    public static byte[] getBytesWithJson(Object data){
        if(data == null){
            return null;
        }
        return JSON.toJSONString(data).getBytes();
    }

    /**
     * 字节码转16进制字符串
     * @param bytes
     * @return
     */
    public static String byte2Hex(byte[] bytes){
        StringBuffer strb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            strb.append(hex.toUpperCase());
        }
        return strb.toString();
    }

    public static byte[] hex2Byte(String strHex){
        if (strHex.length() < 1)
            return null;
        byte[] result = new byte[strHex.length() / 2];
        for (int i = 0; i < strHex.length() / 2; i++) {
            int high = Integer.parseInt(strHex.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(strHex.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 字节数组转JavaObject
     * @param bytes
     * @param clazz
     * @param <T>
     * @return
     */
    public  static  <T> T parseObject(byte[] bytes, Class<T> clazz){
        if(bytes == null){
            return null;
        }
        return JSON.parseObject(bytes, clazz);
    }

}
